package com.whacos.modules.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whacos.common.annotations.Log;
import com.whacos.common.controller.BaseController;
import com.whacos.common.entity.Tree;
import com.whacos.common.enums.Constant;
import com.whacos.common.utils.BeanUtils;
import com.whacos.common.utils.ObjectUtils;
import com.whacos.common.utils.StringUtils;
import com.whacos.common.vo.ResponseVO;
import com.whacos.modules.system.entity.SysDept;
import com.whacos.modules.system.entity.SysRole;
import com.whacos.modules.system.entity.SysUser;
import com.whacos.modules.system.service.DictService;
import com.whacos.modules.system.service.SysRoleService;
import com.whacos.modules.system.service.SysUserService;
import com.whacos.modules.system.vo.FileVO;
import com.whacos.modules.system.vo.SysUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiongdun
 * @description SysUserController
 * @since 2018/11/17 17:11
 */
@RequestMapping("/sys/user")
@Controller
@Slf4j
public class SysUserController extends BaseController {
    private static final String PREFIX = "sys/user";
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private DictService dictService;

    // @Log(value = "跳转到用户信息列表")
    @GetMapping("")
    @RequiresPermissions("sys:user:user")
    public String user() {
        return PREFIX + "/user";
    }

    // @Log(value = "查询用户信息列表")
    @GetMapping("/list")
    @ResponseBody
    public IPage<SysUserVO> list(SysUserVO sysUserVO) {
        // 查询列表数据
        IPage<SysUserVO> sysUserVOPage = new Page<>();
        try {
            // 请求参数
            // 查询
            IPage<SysUser> sysUserPage = sysUserService.page(new Page<>(sysUserVO.getPageNum(), sysUserVO.getPageSize()),
                    Wrappers.lambdaQuery(new SysUser())
                            .eq(StringUtils.isNotEmpty(sysUserVO.getName()), SysUser::getRealName, sysUserVO.getName())
                            .eq(StringUtils.isNotEmpty(sysUserVO.getUsername()), SysUser::getUsername, sysUserVO.getUsername())
                            .eq(ObjectUtils.isNotEmpty(sysUserVO.getDeptId()), SysUser::getDeptId, sysUserVO.getDeptId())
                            .eq(StringUtils.isNotEmpty(sysUserVO.getEmail()), SysUser::getEmail, sysUserVO.getEmail())
                            .eq(StringUtils.isNotEmpty(sysUserVO.getIdCard()), SysUser::getIdCard, sysUserVO.getIdCard())
                            .eq(ObjectUtils.isNotEmpty(sysUserVO.getStatus()), SysUser::getStatus, sysUserVO.getStatus())
                            .orderByAsc(SysUser::getCreatedDate));
            // 返回结果
            BeanUtils.copyPage(sysUserPage, sysUserVOPage);
            List<SysUserVO> sysUserVOList = new ArrayList<>();

            sysUserPage.getRecords().forEach(source -> {
                SysUserVO target = new SysUserVO();
                BeanUtils.copyProperties(source, target);
                sysUserVOList.add(target);
            });
            sysUserVOPage.setRecords(sysUserVOList);
        } catch (Exception e) {
            log.error("查询用户列表异常，异常原因：" + e.getMessage(), e);
        }
        return sysUserVOPage;
    }

    @Log("添加用户")
    @GetMapping("/add")
    @RequiresPermissions("sys:user:add")
    public String add(Model model) {
        List<SysRole> roles = sysRoleService.list();
        model.addAttribute("roles", roles);
        return PREFIX + "/add";
    }

    @Log("编辑用户")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("sys:user:edit")
    public String edit(Model model, @PathVariable("id") Long id) {
        SysUser sysUser = sysUserService.getById(id);
        model.addAttribute("sysUser", sysUser);
        List<SysRole> roles = sysRoleService.listByUserId(id);
        model.addAttribute("roles", roles);
        return PREFIX + "/edit";
    }

    @Log("保存用户")
    @PostMapping("/save")
    @ResponseBody
    @RequiresPermissions("sys:user:add")
    public ResponseVO save(SysUserVO sysUserVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(sysUserVO, sysUser);

            if (sysUserService.save(sysUser)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("保存用户信息异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log("更新用户")
    @PostMapping("/update")
    @ResponseBody
    @RequiresPermissions("sys:user:edit")
    public ResponseVO update(SysUserVO sysUserVO) {
        try {
            if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
                return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
            }
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(sysUserVO, sysUser);

            if (sysUserService.updateById(sysUser)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("更新用户信息异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log("更新用户")
    @PostMapping("/updatePersonal")
    @ResponseBody
    @RequiresPermissions("sys:user:edit")
    public ResponseVO updatePersonal(SysUserVO sysUserVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(sysUserVO, sysUser);
            if (sysUserService.updatePersonal(sysUser) > 0) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("sys:user:remove")
    public ResponseVO remove(@RequestParam(value = "id") Long id) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            if (sysUserService.removeById(id)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("sys:user:batchRemove")
    public ResponseVO batchRemove(@RequestParam("ids[]") List<Long> ids) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            if (sysUserService.batchRemove(ids)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @PostMapping("/exit")
    @ResponseBody
    public boolean exist(SysUser sysUser) {
        // 存在，不通过，false
        return !sysUserService.exist(sysUser);
    }

    @Log("请求更改用户密码")
    @GetMapping("/resetPwd/{id}")
    @RequiresPermissions("sys:user:resetPwd")
    public String resetPwd(@PathVariable("id") Long id, Model model) {
        model.addAttribute("sysUser", new SysUser(id));
        return PREFIX + "/reset_pwd";
    }

    @Log("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    @RequiresPermissions("sys:user:resetPwd")
    public ResponseVO resetPwd(SysUserVO sysUserVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            sysUserService.resetPassword(sysUserVO, this.getUser());
            return ResponseVO.success();
        } catch (Exception e) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, e.getMessage());
        }
    }

    @Log("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    @RequiresPermissions("sys:user:resetPwd")
    public ResponseVO adminResetPwd(SysUserVO sysUserVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            sysUserService.adminResetPassword(sysUserVO);
            return ResponseVO.success();
        } catch (Exception e) {
            return ResponseVO.error(e.getMessage());
        }
    }

    // @Log("获取机构树")
    @GetMapping("/tree")
    @ResponseBody
    public Tree<SysDept> tree() {
        return sysUserService.getDeptTree();
    }

    // @Log("跳转到机构树")
    @GetMapping("/treeView")
    public String treeView() {
        return PREFIX + "/userTree";
    }

    // @Log("获取个人信息页面")
    @GetMapping("/personal")
    public String personal(Model model) {
        SysUser sysUser = sysUserService.getById(this.getUserId());
        model.addAttribute("sysUser", sysUser);
        model.addAttribute("hobbyList", dictService.getHobbyList(sysUser));
        model.addAttribute("sexList", dictService.getSexList());
        return PREFIX + "/personal";
    }

    @Log("上传图片信息")
    @ResponseBody
    @PostMapping("/uploadImg")
    public ResponseVO uploadImg(@RequestParam("avatar_file") MultipartFile avatar_file, String avatar_data, HttpServletRequest request) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            FileVO result = sysUserService.updatePersonalImage(avatar_file, avatar_data, getUserId());
            if (result != null && result.getResult() > 0) {
                return ResponseVO.success(result);
            } else {
                return ResponseVO.error("更新图像失败！");
            }
        } catch (Exception e) {
            return ResponseVO.error("更新图像失败！");
        }
    }
}
